<?php

/**
 * PostsController
 *
 * @author Abo El Seoud
 */
App::import('Model', 'Account');

class PostsController extends AppController {

//	 var $components = array('Auth');

    public $helpers = array('Html', 'Form', 'xls');

    /**
     * Sends data from the DB to the view (index.ctp)
     *
     * @access: public
     *
     * @author "Hussein Abo El Seoud"
     */
    public function index() {
        if ($this->Auth->user('accID') == null) {
            $this->redirect('/posts/fetchHome');
            return;
        }
        $connect = $this->Post->fetchFromTwitter($this->Auth->User('accID'));
        $this->set('connect', $connect);
    }

    /*
     * @access: public
     * @param: null
     * Description: Checks if the user is assigned to an account
     * requests a connection with twitter to fetch the home_timeline
     * then use the JSON object to create an Array with the needed
     * info to display it in the view file.
     * @author Ahmed El-Fouly
     */

    public function fetchHome() {
        $accID = $this->Auth->User('accID');
        $this->set('accID', $accID);
        if ($accID == null) {
            $this->Session->setFlash("You're not assigned to an account, please select an account,
            If you can't find an account contact your admin to assign you to one or more accounts.");
            return;
        }

        $tempAccount = new Account();
        $connection = $tempAccount->connectionRequest($accID);
        if ($connection == false) {
            $this->Session->setFlash("Something went wrong while connecting to twitter.");
            return;
        }
        $status = $connection->get('statuses/home_timeline');
        $timeline = array();
        foreach ($status as $post) {
            $tweet = (array) $post;
            $account = (array) ($tweet['user']);
            $timeline[] = array(
                'postID' => $tweet['id_str'],
                'text' => $tweet['text'],
                'time' => (date("Y-m-d H:i:s", strtotime($tweet['created_at']))),
                'accID' => $account['id_str'],
                'screenName' => $account['screen_name'],
                'image' => $account['profile_image_url'],
                'name' => $account['name'],
                'favorited' => $tweet['favorited'],
                'retweeted' => $tweet['retweeted']);
        }
        $this->set('timeline', $timeline);
    }

    /*
     * Description of "TweetReply"
     *
     * This function works on the main textbox and it allows the user to tweet and reply from the same textbox .
     * The function also allows any editor to post a tweet and added it to the future timeline buffer.

     * @author "Sherif Ismail"
     */

    function TweetReply() {
        $accountID = $this->Auth->User('accID');
        $userID = $this->Auth->User('userID');
        $this->loadModel('User');
        $this->loadModel('FutureTweet');
        $this->loadModel('Tweet');
        $text = $this->request->data['Text'];
        $ReplyName = $this->request->data['ReplyName'];
        $ReplyId = $this->request->data['ReplyId'];
		$image = $this->request->data['image'];
        $empty = 0;
        $JE = 0;
//if (strlen(trim(preg_replace('/\xc2\xa0/', ' ', $this->request->data['Post']['Text']))) == 0) {     
//}
//get the level of permission of the user over this account
        $permission = $this->User->getPermissionLevel($accountID, $userID);
//call the helper method
        $check = $this->helper($userID, $accountID);
        if ($this->User->isAdmin($userID)) {
            $permission = 3;
        }
        if ($permission == 0) {
            $this->Session->setFlash('you are not authorized to view this page');
        } else {
// if helper didnt face any problem with the checks proceed
            if ($check == true) {
//separates the text of the tweeet at every space
                $first = explode(' ', $text);
                $replycheck = strncmp($first[0], $ReplyName, max(strlen($first[0]), strlen($ReplyName))); //checks that the string in the text of the tweet till the first space is the same as the string of the one you want to reply to 
                if ($replycheck == 0 && $ReplyName != null) {//if the session is not null which means someone clicked on reply and the previous check hold execute the following
                    if ($this->Tweet->checkReplyspaces($text, $ReplyName) == false) {
                        $empty = 1;
                    } else {
                        $this->request->data = $this->FutureTweet->setreplyto($this->request->data, '' . $ReplyId);
                    }
                }
                if ($permission == 1) {
                    $JE = 1;
//Sets approval to false, as this is the JE's tweeting part.
                    $this->request->data = $this->FutureTweet->updateapprovedfalse($this->request->data);
                } elseif ($permission == 2 or $permission == 3) {//edited by Menah ElBastawisy
                    $this->request->data = $this->FutureTweet->updateapproved($this->request->data); //set approved to 1 since moderators and editors dont need approval from anyone
                }
                if ($empty == 1) {
                    echo 'Write Something First';
                } else {
					$this->request->data['FutureTweet']['imageName'] = $image;
                    $message = $this->FutureTweet->insertTweet($this->request->data['FutureTweet']);
                    switch ($message) {
                        case 0:
                            if ($JE == 1) {
                                echo 'Tweet was added Successfully and is waiting for approval';
                            } else {
                                echo 'Tweet was added Successfully';
                            }
                            break;
                        case -1:
                            echo 'This Tweet is a duplicate .please change the text';
                            break;
                        case -2:
                            echo 'You have violated the Minimum time duration please try again later';
                            break;
                        case -3:
                            echo 'Internal Error';
                            break;
                    }
                }
            }
        }
        exit();
    }

    /*
     * Description of "helper"
     * @param  "userid","accountid" 
     *
     * This function checks on the tweet if it is valid and if it is not it sends the suitable failure message to the user  .
     * The function also checks if there is a link in the input text and shorten that that link.
     * @author "Sherif Ismail", "Menah ELBastawisy"
     */

    function helper($userID, $accountID) {//edited by sherif ismail, Menah ElBastawisy
        if ($this->request->data) {
            $this->loadModel('Tweet');
            $this->loadModel('FutureTweet');
            $String_TweetText = "" . ($this->request->data['Text']);
            if (strlen(trim(preg_replace('/\xc2\xa0/', ' ', $String_TweetText))) == 0) {
                echo 'Write something First';
            } else {
                if ($this->Tweet->overlength($String_TweetText)) {
                    $current_time = date('Y-m-d H:i:s');
                    $this->request->data = $this->FutureTweet->update($current_time, $userID, $String_TweetText, $accountID);
                    return true;
                } else {
                    echo 'Your Tweet exceeded 140 chars';
                }
            }
        }
        return false;
    }

    /**
     * Views a certain post (Sends the data of that specific post from the DB to the view (view.ctp))
     * 
     * @access: public
     * @param: string $postID; the id of the post to be viewed
     *
     * @author "Hussein Abo El Seoud"
     */
    public function view($postID = NULL) {
        $this->set('posts', $this->Post->query("select * from posts Post join accounts Account on Post.accID=Account.accID where Post.postID='" . $postID . "'"));
    }

    /*
     * @access: public
     * @param: $screenName, $name, $text, $text
     * @Description: Sets 4 variables for the view file to display when a tweet is clicked.
     */

    public function viewTweet($screenName, $name, $text, $time) {
        $this->set('screenName', $screenName);
        $this->set('name', $name);
        $this->set('text', $text);
        $this->set('time', $time);
    }

    /* Description of pages()
     * @param: Nothing
     * The function retrieves the selected value from the dropdown menu
     * and then redircets to the viewtweets($paging) fucntion
     *
     * @author: Omar Safwany
     */

    function pages() {
        if ($this->request->data) {
            $searchKey = $this->request->data['Post']['Display per page'];

            $type = $this->request->data['Post']['Display per page'];

            switch ($type) {
                case '0': $this->redirect(array('action' => 'viewtweets', 1));
                case '1': $this->redirect(array('action' => 'viewtweets', 5));
                case '2': $this->redirect(array('action' => 'viewtweets', 25));
                case '3': $this->redirect(array('action' => 'viewtweets', 50));
                case '4': $this->redirect(array('action' => 'viewtweets', 100));
            }
        }
    }

    /* Description of "viewtweets($paging)"
     * @param: $paging "The number of records to be displayed per page"
     *
     * Description of the function:
     * The function returns all the history tweets
     * First, it checks if the user is permitted to view the history
     * If the user has no permission, A message is displayed stating that he has no permission to view anything
     * If he has permission, it continues as follows
     * If tweets are found, they're displayed to the user
     * If the database is empty, it displays a message stating that.
     *
     * @author "Omar Safwany"
     */

    function viewtweets($paging) {
        $options = array(
            'table' => 'tweets',
            'alias' => 'Tweet',
            'type' => 'inner',
            'conditions' => array(
                'Tweet.postID = Post.postID'
            )
        );

        $options2['joins'] = array(
            array('table' => 'tweets',
                'alias' => 'Tweet',
                'type' => 'INNER',
                'order' => array('Post.postID' => 'desc'),
                'conditions' => array(
                    'Tweet.postID = Post.postID'
                )
                ));

        //counting number of results
        $count = $this->Post->find('count', $options2);

        //checking the permission level
        if (($this->Auth->user('admin')) == 0) {
            $result = null;
            $this->set('result', $result);
            $this->Session->SetFlash('You have no authorization to view the history');
            $this->redirect(array('action' => 'fetchHome'));
        } else {
            if ($count == 0) {
                $this->Session->SetFlash('No tweets in the database yet.');
            } else {
                //$this->paginate works on creating pages to display certain amount of data in it
                //the value of $paging represents the number of records to be displayed per page
                //as requested by the user

                $this->paginate = array(
                    'fields' => array('*'),
                    'limit' => $paging,
                    'joins' => array($options),
                    'order' => array('Post.time' => 'desc'));
                $result = $this->paginate('Post');
                $this->set(compact('result'));
            }
        }
    }

    /*
     * Description of "tweetreplies"
     * @param: postID
     *
     * Description of the function:
     * This function gets the replies of a certain tweet
     * It simply takes an the id of the tweet and searches the database for all tweets replying to it
     * If replies are found, it displays them
     * If no replies are found for this tweet, it just states NO replies found
     *
     * @author "Omar Safwany"
     */

    function tweetreplies($id = Null) {
        $options2['joins'] = array(
            array('table' => 'tweets',
                'alias' => 'Tweet',
                'type' => 'INNER',
                'order' => array('Post.postID' => 'desc'),
                'conditions' => array(
                    'Post.postID' => $id,
                    'Tweet.postID = Post.postID'
                )
                ));

        $au = ClassRegistry::init('User')->getPermissionLevel($this->Auth->User('accID'), $this->Auth->User('userID'));
        $fav = ClassRegistry::init('Tweet')->getFav($id);
        $ret = $this->requestAction('/tweets/getNumberRetweet/' . $id);


        $originaltweet = $this->Post->find('all', $options2);

        $this->set('originaltweet', $originaltweet);
        $this->set('favourites', $fav);
        $this->set('retweets', $ret);
        $this->set('id', $id);

        //Again, here we're setting the search conditions and the type of join
        $options1['joins'] = array(
            array('table' => 'tweets',
                'alias' => 'Tweet',
                'type' => 'INNER',
                'order' => array('Post.postID' => 'desc'),
                'conditions' => array(
                    'Tweet.postID = Post.postID',
                    'Tweet.replyTo' => $id
                )
                ));

        //fetching all matching results
        $reply = $this->Post->find('all', $options1);

        //counting the number of fetched results;
        $count = $this->Post->find('count', $options1);
        $this->set('reply', $reply);


        if (($this->Auth->user('admin')) == 0) {
            $reply = null;
            $this->set('reply', $reply);
            $this->Session->SetFlash('You have no authorization to view anything)');
            $this->redirect(array('action' => 'fetchHome'));
        } else {
            if ($count == 0) {
                $this->Session->SetFlash("This tweet has no replies..YET");
            } else {
                $this->set('retweets', $ret);

                $this->set('fav', $fav);
                $this->set('reply', $reply);
            }
        }
    }

    /*
     * Description of "deleteTweets($postID)"
     * @param: $postID
     *
     * Description of the function:
     * This function deletes the selected tweet and all of its details from the database completely
     *
     * @author "Omar Safwany"
     */

    function deleteTweets($postID) {

        $options['joins'] = array(
            array('table' => 'tweets',
                'alias' => 'Tweet',
                'type' => 'INNER',
                'order' => array('Post.postID' => 'desc'),
                'conditions' => array(
                    'Post.postID' => $postID,
                    'Tweet.postID = Post.postID'
                )
                ));

        $originaltweet = $this->Post->find('all', $options);

        if (($this->Auth->user('admin')) == 0) {
            $this->Session->SetFlash("You are not authorized to delete anything.");
            $this->redirect(array('action' => 'fetchHome'));
        } else {

            if ($originaltweet == null) {
                $this->Session->SetFlash('Either no such tweet exists or it has already been deleted previously.');
                $this->redirect(array('action' => 'fetchHome'));
            } else {
                $this->Post->deleteTweets($postID);

                $this->Session->SetFlash('The tweet has been deleted successfully.');
                $this->redirect(array('action' => 'pages'));
            }
        }
    }
	
	/*
     * Description of "deleteAll($userID)"
     * @param: $postID
     *
     * Description of the function:
     * This function deletes all tweets of the selected user from the database completely
     *
     * @author "Omar Safwany"
     */
	public function deleteAll($userID)
	{
		if (($this->Auth->user('admin')) == 0) {
            $this->Session->SetFlash("You are not authorized to delete anything.");
            $this->redirect(array('action' => 'fetchHome'));
        } else {
                $this->Post->deleteAll($userID);

                $this->Session->SetFlash('The accounts tweets have been deleted successfully.');
                $this->redirect(array('action' => 'fetchHome'));           
        }
	}

    /*
     * Description of "filter"
     * @param  
     * @return no return
     * description of the function:The function filter the mentions by date it checks that the 
     * user has permission to view data first then it checks that the date 
     * fields have values in it takes the values and put them in two variables 
     * add to them the time time wichis equal to zero ansave them in variables of type dateTime
     * then it checks which value is the start date and which is the end date and filter accordingly
     * if both dates were the same then the function will return the mentions on that day only.
     *
     * @author "Noha Diaa"
     */

    public function filter() {

        $this->set('result', null);
        if ($this->request->data) {
            $au = ClassRegistry::init('User')->getPermissionLevel($this->Auth->User('accID'), $this->Auth->User('userID'));
            if ($au > 2 || ($this->Auth->user('admin')) == 1) {
                if (!empty($this->request->data['Post']['Date1 (dd/mm/yyyy)'])) {
                    if (!empty($this->request->data['Post']['Date2 (dd/mm/yyyy)'])) {

                        $date1 = $this->request->data['Post']['Date1 (dd/mm/yyyy)'];
                        $date2 = $this->request->data['Post']['Date2 (dd/mm/yyyy)'];

                        list($Date1Day, $Date1Month, $Date1Year) = split('[/.-]', $date1);
                        list($Date2Day, $Date2Month, $Date2Year) = split('[/.-]', $date2);
                        $Date1Hour = '00';
                        $Date1Minute = '00';
                        $Date1Second = '00';

                        $Date2Hour = '00';
                        $Date2Minute = '00';
                        $Date2Second = '00';

                        $dateTime1 = $Date1Year . '-' . $Date1Month . '-' . $Date1Day . ' ' . $Date1Hour . ':' . $Date1Minute . ':' . $Date1Second;
                        $dateTime2 = $Date2Year . '-' . $Date2Month . '-' . $Date2Day . ' ' . $Date2Hour . ':' . $Date2Minute . ':' . $Date2Second;
                        $dateTime1 = new DateTime($dateTime1);
                        $dateTime2 = new DateTime($dateTime2);

                        if ($dateTime1 > $dateTime2) {
                            $startdate = (array) $dateTime2;
                            $enddate = (array) $dateTime1;
                            $options ['joins'] = array(
                                array('table' => 'tweets',
                                    'alias' => 'Tweet',
                                    'type' => 'INNER',
                                    'order' => array('Post.postID' => 'desc'),
                                    'conditions' => array(
                                        'Tweet.postID=Post.postID',
                                        'Tweet.subTime >=' => $startdate['date'],
                                        'Tweet.subTime <=' => $enddate['date'],
                                        'Tweet.isMention' => 0,
                                        'Post.accID' => $this->Auth->User('accID')
                                    )
                                )
                            );

                            $tweets = $this->Post->find('all', $options);
                            //$tweets = $this->Post->query("select * from posts");
                            $this->set('result', $tweets);
                        } else {
                            if ($dateTime1 < $dateTime2) {
                                $startdate = (array) $dateTime1;
                                $enddate = (array) $dateTime2;
                                $options1 ['joins'] = array(
                                    array('table' => 'tweets',
                                        'alias' => 'Tweet',
                                        'type' => 'INNER',
                                        'order' => array('Tweet.postID' => 'desc'),
                                        'conditions' => array(
                                            'Tweet.postID=Post.postID',
                                            'Tweet.subTime >=' => $startdate['date'],
                                            'Tweet.subTime <=' => $enddate['date'],
                                            'Tweet.isMention' => 0,
                                            'Post.accID' => $this->Auth->User('accID')
                                        )
                                    )
                                );
                                $tweets = $this->Post->find('all', $options1);
                                $this->set('result', $tweets);
                            } else {
                                $startdate = (array) $dateTime1;
                                $options2 ['joins'] = array(
                                    array('table' => 'tweets',
                                        'alias' => 'Tweet',
                                        'type' => 'INNER',
                                        'order' => array('Tweet.postID' => 'desc'),
                                        'conditions' => array(
                                            'Tweet.postID=Post.postID',
                                            'Tweet.subTime ' => $startdate['date'],
                                            'Tweet.isMention' => 0,
                                            'Post.accID' => $this->Auth->User('accID')
                                        )
                                    )
                                );
                                $tweets = $this->Post->find('all', $options2);
                                $this->set('result', $tweets);
                            }
                        }
                        if (empty($tweets)) {
                            $this->Session->setFlash('No tweets matching your search criteria');
                        }
                    } else {
                        $this->Session->setFlash('end date was not specified');
                    }
                } else {
                    $this->Session->setFlash('please enter a start date');
                }
                return $tweets;
            } else {
                $this->Session->setFlash('you are not authorized to filter by date');
            }
        }
    }

    /*
     * Description of "filtermentions"
     * @param  
     * @return no return
     * description of the function:The function filter the mentions by date it checks that the 
     * user has permission to view data first then it checks that the date 
     * fields have values in it takes the values and put them in two variables 
     * add to them the time time wichis equal to zero ansave them in variables of type dateTime
     * then it checks which value is the start date and which is the end date and filter accordingly
     * if both dates were the same then the function will return the mentions on that day only.
     *
     * @author "Noha Diaa"
     */

    public function filtermentions() {
        $this->set('result', null);
        if ($this->request->data) {
            $au = ClassRegistry::init('User')->getPermissionLevel($this->Auth->User('accID'), $this->Auth->User('userID'));
            if ($au > 2 || ($this->Auth->user('admin')) == 1) {
                if (!empty($this->request->data['Post']['Date1 (dd/mm/yyyy)'])) {
                    if (!empty($this->request->data['Post']['Date2 (dd/mm/yyyy)'])) {

                        $date1 = $this->request->data['Post']['Date1 (dd/mm/yyyy)'];
                        $date2 = $this->request->data['Post']['Date2 (dd/mm/yyyy)'];

                        list($Date1Day, $Date1Month, $Date1Year) = split('[/.-]', $date1);
                        list($Date2Day, $Date2Month, $Date2Year) = split('[/.-]', $date2);
                        $Date1Hour = '00';
                        $Date1Minute = '00';
                        $Date1Second = '00';

                        $Date2Hour = '00';
                        $Date2Minute = '00';
                        $Date2Second = '00';


                        $dateTime1 = $Date1Year . '-' . $Date1Month . '-' . $Date1Day . ' ' . $Date1Hour . ':' . $Date1Minute . ':' . $Date1Second;
                        $dateTime2 = $Date2Year . '-' . $Date2Month . '-' . $Date2Day . ' ' . $Date2Hour . ':' . $Date2Minute . ':' . $Date2Second;
                        $dateTime1 = new DateTime($dateTime1);
                        $dateTime2 = new DateTime($dateTime2);

                        if ($dateTime1 > $dateTime2) {
                            $startdate = (array) $dateTime2;
                            $enddate = (array) $dateTime1;
                            $options ['joins'] = array(
                                array('table' => 'tweets',
                                    'alias' => 'Tweet',
                                    'type' => 'INNER',
                                    'order' => array('Post.postID' => 'desc'),
                                    'conditions' => array(
                                        'Tweet.postID=Post.postID',
                                        'Tweet.subTime >=' => $startdate['date'],
                                        'Tweet.subTime <=' => $enddate['date'],
                                        'Tweet.isMention' => 1,
                                        'Post.accID' => $this->Auth->User('accID')
                                    )
                                )
                            );
                            $tweets = $this->Post->find('all', $options);
                            $this->set('result', $tweets);
                        } else {
                            if ($dateTime1 < $dateTime2) {
                                $startdate = (array) $dateTime1;
                                $enddate = (array) $dateTime2;
                                $options2 ['joins'] = array(
                                    array('table' => 'tweets',
                                        'alias' => 'Tweet',
                                        'type' => 'INNER',
                                        'order' => array('Tweet.postID' => 'desc'),
                                        'conditions' => array(
                                            'Tweet.postID=Post.postID',
                                            'Tweet.subTime >=' => $startdate['date'],
                                            'Tweet.subTime <=' => $enddate['date'],
                                            'Tweet.isMention' => 1,
                                            'Post.accID' => $this->Auth->User('accID')
                                        )
                                    )
                                );
                                $tweets = $this->Post->find('all', $options2);
                                $this->set('result', $tweets);
                            } else {
                                $startdate = (array) $dateTime1;
                                $options1 ['joins'] = array(
                                    array('table' => 'tweets',
                                        'alias' => 'Tweet',
                                        'type' => 'INNER',
                                        'order' => array('Tweet.postID' => 'desc'),
                                        'conditions' => array(
                                            'Tweet.postID=Post.postID',
                                            'Tweet.subTime ' => $startdate['date'],
                                            'Tweet.isMention' => 1,
                                            'Post.accID' => $this->Auth->User('accID')
                                        )
                                    )
                                );
                                $tweets = $this->Post->find('all', $options1);
                                debug($tweets);
                                $this->set('result', $tweets);
                            }
                        }
                        if (empty($tweets)) {
                            $this->Session->setFlash('No mentions matching your search criteria');
                        }
                    } else {
                        $this->Session->setFlash('end date was not specified');
                    }
                } else {
                    $this->Session->setFlash('please enter a start date');
                }
            } else {
                $this->Session->setFlash('you are not authorized to filter by date');
            }
        }
    }

    /*
     * Description of "getEventTweets"
     * @param  'eventID' as $eventID
     *
     * description of the function:
     * This function's purpose is to retrieve all the text for the tweets
     * related to a certain event,It calls the function getEventTweets($id)
     * in Post Model and then it takes the returned array of tweets and
     * set the function view with the result,also it handles some conditions
     * of entering a wrong 'eventID' and the case of empty DataBase
     * @author "Mo'men el Sawy"
     */

    function getEventTweets($eventID = NULL) {


        $result = $this->Post->getEventTweets($eventID);
        debug($result);

        if ($result == -1) {    //The model returns an indication of an empty table
            $this->Session->setFlash('The Database is still empty');
        } else if (!empty($result)) {
            $this->set('eventTweets', $result);
        } else {
            $this->Session->setFlash('No Events\' tweets to be displayed');
            $this->set('eventTweets', NULL);
        }
    }

    /*
     * Description of "getMentions"
     *
     * description of the function:
     * The function logic is to get every tweet in the database history
     * has a mention and displays these mentions for the use and this
     * happens by calling getMention() method in the 'Post' Model
     * and then it takes the returned array of mentions and set them
     * to be viewed in the view for the function
     * @author "Mo'men el Sawy"
     */

    function getMentions() {

        $result = $this->Post->getMentions();
        debug($result);
        if ($result == -1) {               //The model returns an indication of an empty table
            $this->Session->setFlash('The Database is still empty');
        } else if (!empty($result)) {
            $this->set('mention', $result);
        } else {
            $this->Session->setFlash('No Events\' tweets to be displayed');
            $this->set('mention', NULL);
        }
    }

    /**
     * Description of function "export"
     * @param string $postID
     * @return void 
     * 
     * Description :
     * A function taking the post ID as an input and checks if current user have
     * enough permissions and then exports tweet's data to excel file and downloads it 
     * automatically to check it.  
     * 
     * @author "Omar Elshal"
     */
    function export($postID = NULL) {

        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');

        $permissionLevel = ClassRegistry::init('User')->getPermissionLevel($accID, $userID);

        if ($accID == null) {
            $this->Session->setFlash('You are not logged in into any account!');
        }

        if ($this->Auth->User('admin')) {

            $tweets = $this->Post->export($postID);
            //debug($tweets);

            $this->set('models', $tweets);
        } else {
            $this->Session->setFlash("You are not authorized to do this action! ");
            $this->redirect(array('controller' => 'users', 'action' => 'viewUsers'));
        }
    }

    /**
     * Description of filterTweetsByUser($userID)
     * @param string $userID 
     * @access public
     *
     * Description of the function:
     * The function takes the user ID as an input and returns his tweets
     * @author "OmarElshal"
     */
    function filterTweetsByUser($userID = NULL) {

        $userID1 = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        //$accID = 19432286;
        $permissionLevel = ClassRegistry::init('User')->getPermissionLevel($accID, $userID1);
        // debug($permissionLevel);
        if ($accID == null) {
            $this->Session->setFlash('You are not logged in into any account!');
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
        if (($permissionLevel == 3) || ($this->Auth->User('admin'))) {

            
            $this->loadModel('User');

            $option5['join'] = array(
                array('table' => 'users',
                    'alias' => 'User'
                )
            );
            $option5['conditions'] = array('User.userID' => $userID);
            $count = $this->User->find('count', $option5);
            if ($count != 0) {

                if ($userID != NULL) {
                    $values['joins'] = array(
                        array('table' => 'tweets',
                            'alias' => 'Tweet',
                            'type' => 'INNER',
                            'order' => array('Post.postID' => 'desc'),
                            'conditions' => array('Tweet.postID = Post.postID', 'Post.userID' => $userID, 'Tweet.isMention' => 0)
                            ));

                    $result = $this->Post->find('all', $values);
                    $counter = $this->Post->find('count', $values);
                }
                if ($counter != 0) {

                    $this->set('result', $result);
                } else {
                    $this->Session->setFlash('No tweets for this user');
                    $this->redirect(array('controller' => 'users', 'action' => 'viewUsers'));
                }
            } else {
                $this->Session->setFlash('user does not exist');
				$this->redirect(array('controller' => 'users', 'action' => 'index'));
            }
        } else {
            $this->Session->setFlash("You are not authorized to view this page! ");
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
    }

    /**
     * Description of function "viewDirectMessages": 
     * @param string $accID
     * @access public
     *
     * Description of the function:
     * A function taking the account(client) ID as an input and returns client's direct messages
     * @author "Omar Elshal"
     */
    function viewDirectMessages($accID = NULL) {



        $userID = $this->Auth->User('userID');
        $accID1 = $this->Auth->User('accID');

        $permissionLevel = ClassRegistry::init('User')->getPermissionLevel($accID1, $userID);

        if ($accID1 == null) {
            $this->Session->setFlash('You are not logged in into any account!');
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }

        if (($permissionLevel == 3) || ($this->Auth->User('admin'))) {

            echo $accID;
            $this->loadModel('Account');
            //$accExists = $this->Account->query("Select accID from accounts where accounts.accID = '".$accID."'");
            $options['join'] = array(
                array('table' => 'accounts',
                    'alias' => 'Account'
                )
            );
            $options['conditions'] = array('Account.accID' => $accID);
            $count = $this->Account->find('count', $options);

            if ($count != 0) {
                //  print_r($accExists); 
                if ($accID != NULL) {
                    $this->loadModel('Post');

                    $val['joins'] = array(
                        array('table' => 'direct_messages',
                            'alias' => 'DirectMessage',
                            'type' => 'INNER',
                            'order' => array('Post.postID' => 'desc'),
                            'conditions' => array('Post.postID = DirectMessage.postID', 'Post.accID' => $accID)
                            ));

                    $result = $this->Post->find('all', $val);
                    $counter = $this->Post->find('count', $val);
                }

                if ($counter != 0) {
                    $this->set('result', $result);
                } else {
                    $this->Session->setFlash('No Direct Messages for this client');
                    $this->redirect(array('controller' => 'accounts', 'action' => 'viewClients'));
                }
            } else {
                $this->Session->setFlash('no such account');
				$this->redirect(array('controller' => 'users', 'action' => 'index'));
            }
        } else {
            $this->Session->setFlash("You are not authorized to view this page! ");
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
    }

    /**
     * Description of function "viewUserDirectMessages"
     * @param string $userID 
     * @access public
     *
     * Description of the function:
     * A function taking the user ID as an input and returns user's direct messages
     *  made by him through the client he is working for
     * @author "Omar Elshal"
     */
    function viewUserDirectMessages($userID = NULL) {



        $userID1 = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');

        $permissionLevel = ClassRegistry::init('User')->getPermissionLevel($accID, $userID1);

        if ($accID == null) {
            $this->Session->setFlash('You are not logged in into any account!');
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }

        if (($permissionLevel == 3) || ($this->Auth->User('admin'))) {

            echo $accID;
            $this->loadModel('Account');
            //$accExists = $this->Account->query("Select accID from accounts where accounts.accID = '".$accID."'");
            $options['join'] = array(
                array('table' => 'accounts',
                    'alias' => 'Account'
                )
            );
            $options['conditions'] = array('Account.accID' => $accID);
            $count = $this->Account->find('count', $options);

            if ($count != 0) {
                //  print_r($accExists); 
                if ($accID != NULL) {
                    $this->loadModel('Post');

                    $val['joins'] = array(
                        array('table' => 'direct_messages',
                            'alias' => 'DirectMessage',
                            'type' => 'INNER',
                            'order' => array('Post.postID' => 'desc'),
                            'conditions' => array('Post.postID = DirectMessage.postID', 'Post.userID' => $userID)
                            ));

                    $result = $this->Post->find('all', $val);
                    $counter = $this->Post->find('count', $val);
                }

                if ($counter != 0) {
                    $this->set('result', $result);
                } else {
                    $this->Session->setFlash('No Direct Messages by this user');
                    $this->redirect(array('controller' => 'users', 'action' => 'viewUsers'));
                }
            } else {
                $this->Session->setFlash('no such account');
				$this->redirect(array('controller' => 'users', 'action' => 'index'));
            }
        } else {
            $this->Session->setFlash("You are not authorized to view this page! ");
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
    }

    /**
     * Description of function "search": 
     * @param no parameters
     * @access public
     * @return no return
     * Description of the function:
     * A function searching for a text in the tweets texts it takes the text from the text box in the view
     * @author "Noha Diaa"
     */
    public function Search() {
        $this->set('result', null);
        if ($this->request->data) {
            if (($this->Auth->user('admin')) == 1) {
                $text = $this->request->data['Post']['text'];

                $options ['joins'] = array(
                    array('table' => 'tweets',
                        'alias' => 'Tweet',
                        'type' => 'INNER',
                        'order' => array('Post.postID' => 'desc'),
                        'conditions' => array('AND' => array(
                                array('Tweet.postID=Post.postID'),
                                array('Post.text LIKE ' => '%' . $text . '%')
                            )
                        )
                    )
                );

                $tweets = $this->Post->find('all', $options);
                $this->set('result', $tweets);
                if (empty($tweets)) {
                    $this->Session->setFlash('No tweets matching your search criteria');
                }
            } else {

                $this->Session->setFlash('you are not authorized to filter by date');
            }
        }
    }

    /*
     * Description of function "deletedm"
     * @param string $PostID 
     * 
     *
     * Description of the function:
     * A function taking the post ID as an input and deletes the direct message with this ID from twitter
     * @author "Mark Milad"
     */

    public function deletedm($PostID) {
        $this->loadModel('DirectMessage');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $permissionLevel = ClassRegistry::init('User')->getPermissionLevel($accID, $userID);

         if ($accID == null) {
            $this->Session->setFlash('You are not logged in into any account!');
            $this->redirect('/');
        }
        if (($permissionLevel > 1) || ($this->Auth->User('admin'))) {

        $tempAccount = new Account();
        $request = (array) $tempAccount->connectionRequest($this->Auth->User('accID'))->delete('direct_messages/destroy', array('id' => $PostID));
        debug($request);
        if(count($request) != 2){

        $this->DirectMessage->deleteOne($PostID);
        $this->Post->deleteThisPost($PostID);
        $this->Session->setFlash('Successfully deleted');
        
        $this->redirect('/posts');
        }
        else {
            $this->DirectMessage->deleteOne($PostID);
            $this->Post->deleteThisPost($PostID);
            $this->Session->setFlash($request['error'] . ".. says Twitter");
            $this->redirect('/posts');
        }

    }
    else {
             $this->Session->setFlash('You are not authorized to delete this post');
                $this->redirect('/posts');
        }
    }

    /*
     * Description of function "deletetweet"
     * @param string $tweetID 
     * 
     *
     * Description of the function:
     * A function taking the tweet ID as an input and deletes the tweet with this ID from twitter
     * @author "Mark Milad"
     */

    public function deletetweet($tweetID) {
        $this->loadModel('Tweet');
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $permissionLevel = ClassRegistry::init('User')->getPermissionLevel($accID, $userID);

         if ($accID == null) {
            $this->Session->setFlash('You are not logged in into any account!');
            $this->redirect('/');
        }
        if (($permissionLevel > 1) || ($this->Auth->User('admin'))) {

        $tempAccount = new Account();
        $request = (array) $tempAccount->connectionRequest($this->Auth->User('accID'))->post('statuses/destroy', array('id' => $tweetID));

        if (count($request) != 2) {

            if ($this->Tweet->deleteOne($tweetID) && $this->Post->deleteThisPost($tweetID)) {
                $this->Session->setFlash('Successfully deleted');
                $this->redirect('/posts');
            } else {
                $this->Session->setFlash('Something went wrong .. deletion unsuccessful');
                $this->redirect('/posts');
            }
        } else {
            $this->Session->setFlash($request['error'] . ".. says Twitter");
            $this->redirect('/posts');
        }
        }
        else {
             $this->Session->setFlash('You are not authorized to delete this post');
                $this->redirect('/posts');
        }
    }

    /*
     * Description of function "joiningnodate"
     * @param $text
     * 
     * @return $tweets
     * Description of the function:
     * A function that takes as input text and 
     * return all the tweets with the text in the tweet body
     * @author "Noha Diaa"
     */

    public function joiningnodate($text) {

        $options1 ['joins'] = array(
            array('table' => 'tweets',
                'alias' => 'Tweet',
                'type' => 'INNER',
                'order' => array('Tweet.postID' => 'desc'),
                'conditions' => array(
                    'Tweet.postID=Post.postID',
                    'Post.text LIKE ' => '%' . $text . '%',
                    'Post.accID' => $this->Auth->User('accID')
                )
            )
        );
        return $tweets = $this->Post->find('all', $options1);
    }

    /*
     * Description of function "joiningtweetsnodate"
     * @param $text
     * 
     * @return $tweets
     * Description of the function:
     * A function that takes as input text and 
     * return all the tweets with the text in the tweet body
     * @author "Noha Diaa"
     */

    public function joiningtweetssnodate($text) {

        $options1 ['joins'] = array(
            array('table' => 'tweets',
                'alias' => 'Tweet',
                'type' => 'INNER',
                'order' => array('Tweet.postID' => 'desc'),
                'conditions' => array(
                    'Tweet.postID=Post.postID',
                    'Tweet.isMention' => 0,
                    'Post.text LIKE ' => '%' . $text . '%',
                    'Post.accID' => $this->Auth->User('accID')
                )
            )
        );
        return $tweets = $this->Post->find('all', $options1);
    }

    /*
     * Description of function "joiningtweets"
     * @param $startdate,$enddate,$text
     * 
     * @return $tweets
     * Description of the function:
     * A function that takes as input startdate,enddate and text and 
     * return all the tweets in the range of the date with the text in the tweet body
     * @author "Noha Diaa"
     */

    public function joiningtweets($startdate, $enddate, $text) {

        $options1 ['joins'] = array(
            array('table' => 'tweets',
                'alias' => 'Tweet',
                'type' => 'INNER',
                'order' => array('Tweet.postID' => 'desc'),
                'conditions' => array(
                    'Tweet.postID=Post.postID',
                    'Tweet.subTime >=' => $startdate['date'],
                    'Tweet.subTime <=' => $enddate['date'],
                    'Tweet.isMention' => 0,
                    'Post.text LIKE ' => '%' . $text . '%',
                    'Post.accID' => $this->Auth->User('accID')
                )
            )
        );
        return $tweets = $this->Post->find('all', $options1);
    }

    /*
     * Description of function "joiningmentionsnodate"
     * @param $text
     * 
     * @return $tweets
     * Description of the function:
     * A function that takes as input text and 
     * return all the tweets with the text in the tweet body
     * @author "Noha Diaa"
     */

    public function joiningmentionsnodate($text) {

        $options1 ['joins'] = array(
            array('table' => 'tweets',
                'alias' => 'Tweet',
                'type' => 'INNER',
                'order' => array('Tweet.postID' => 'desc'),
                'conditions' => array(
                    'Tweet.postID=Post.postID',
                    'Tweet.isMention' => 1,
                    'Post.text LIKE ' => '%' . $text . '%',
                    'Post.accID' => $this->Auth->User('accID')
                )
            )
        );
        return $tweets = $this->Post->find('all', $options1);
    }

    /*
     * Description of function "joiningmentions"
     * @param $startdate,$enddate,$text
     * 
     * @return $tweets
     * Description of the function:
     * A function that takes as input startdate,enddate and text and 
     * return all the tweets in the range of the date with the text in the tweet body
     * @author "Noha Diaa"
     */

    public function joiningmentions($startdate, $enddate, $text) {

        $options1 ['joins'] = array(
            array('table' => 'tweets',
                'alias' => 'Tweet',
                'type' => 'INNER',
                'order' => array('Tweet.postID' => 'desc'),
                'conditions' => array(
                    'Tweet.postID=Post.postID',
                    'Tweet.subTime >=' => $startdate['date'],
                    'Tweet.subTime <=' => $enddate['date'],
                    'Tweet.isMention' => 1,
                    'Post.text LIKE ' => '%' . $text . '%',
                    'Post.accID' => $this->Auth->User('accID')
                )
            )
        );
        return $tweets = $this->Post->find('all', $options1);
    }

    /*
     * Description of function "getDate"
     * @param none 
     * 
     * @return date
     * Description of the function:
     * A function that takes as input the date from the datepicker parse it 
     * and make it in the same form to be compared to the dates in the database
     * @author "Noha Diaa"
     */

    public function getDate($date1) {
        list($Date1Day, $Date1Month, $Date1Year) = split('[/.-]', $date1);
        $Date1Hour = '00';
        $Date1Minute = '00';
        $Date1Second = '00';
        $dateTime1 = $Date1Year . '-' . $Date1Month . '-' . $Date1Day . ' ' . $Date1Hour . ':' . $Date1Minute . ':' . $Date1Second;
        return $dateTime1;
    }

    /*
     * Description of function "allfilters"
     * @param none 
     * 
     * @return no return
     * Description of the function:
     * A function for all the filters combined
     * @author "Noha Diaa"
     */

    public function allfilters() {
        $this->set('result', $this->joiningnodate(''));
        if ($this->request->data) {
            if (($this->Auth->user('admin')) == 1) {
                if (($this->request->data['Post']['type'] == 'T') && (
                        (!empty($this->request->data['Post']['Start date (dd/mm/yyyy)']))
                        && (!empty($this->request->data['Post']['End date (dd/mm/yyyy)'])))) {
                    if (empty($this->request->data['Post']['text'])) {
                        $text = '';
                    } else {
                        $text = $this->request->data['Post']['text'];
                    }
                    $date1 = $this->request->data['Post']['Start date (dd/mm/yyyy)'];
                    $date2 = $this->request->data['Post']['End date (dd/mm/yyyy)'];
                    $dateTime1 = new DateTime($this->getDate($date1));
                    $dateTime2 = new DateTime($this->getDate($date2));

                    if ($dateTime1 > $dateTime2) {
                        $this->Session->setFlash('please enter a correct date range');
                    } else {
                        if ($dateTime1 < $dateTime2) {
                            $startdate = (array) $dateTime1;
                            $enddate = (array) $dateTime2;
                            $tweets = $this->joiningtweets($startdate, $enddate, $text);
                            $this->set('result', $this->joiningtweets($startdate, $enddate, $text));
                        } else {
                            $startdate = (array) $dateTime1;
                            $tweets = $this->joiningtweets($startdate, $startdate, $text);
                            $this->set('result', $this->joiningtweets($startdate, $startdate, $text));
                        }
                    }
                }
                if (($this->request->data['Post']['type'] == 'M') && (
                        (!empty($this->request->data['Post']['Start date (dd/mm/yyyy)']))
                        && (!empty($this->request->data['Post']['End date (dd/mm/yyyy)'])))) {
                    if (empty($this->request->data['Post']['text'])) {
                        $text = '';
                    } else {
                        $text = $this->request->data['Post']['text'];
                    }

                    $date1 = $this->request->data['Post']['Start date (dd/mm/yyyy)'];
                    $date2 = $this->request->data['Post']['End date (dd/mm/yyyy)'];

                    $dateTime1 = new DateTime($this->getDate($date1));
                    $dateTime2 = new DateTime($this->getDate($date2));

                    if ($dateTime1 > $dateTime2) {
                        $this->Session->setFlash('please enter a correct date range');
                    } else {
                        if ($dateTime1 < $dateTime2) {
                            $startdate = (array) $dateTime1;
                            $enddate = (array) $dateTime2;
                            $tweets = $this->joiningmentions($startdate, $enddate, $text);
                            $this->set('result', $this->joiningmentions($startdate, $enddate, $text));
                        } else {
                            $startdate = (array) $dateTime1;
                            $tweets = $this->joiningmentions($startdate, $startdate, $text);
                            $this->set('result', $this->joiningmentions($startdate, $startdate, $text));
                        }
                    }
                }
                if (($this->request->data['Post']['type'] == 'M') && (
                        (empty($this->request->data['Post']['Start date (dd/mm/yyyy)']))
                        && (empty($this->request->data['Post']['End date (dd/mm/yyyy)'])))) {
                    if (empty($this->request->data['Post']['text'])) {
                        $text = '';
                    } else {
                        $text = $this->request->data['Post']['text'];
                    }
                    $tweets = $this->joiningmentionsnodate($text);
                    $this->set('result', $this->joiningmentionsnodate($text));
                }
                if (($this->request->data['Post']['type'] == 'T') && (
                        (empty($this->request->data['Post']['Start date (dd/mm/yyyy)']))
                        && (empty($this->request->data['Post']['End date (dd/mm/yyyy)'])))) {
                    if (empty($this->request->data['Post']['text'])) {
                        $text = '';
                    } else {
                        $text = $this->request->data['Post']['text'];
                    }
                    $tweets = $this->joiningtweetssnodate($text);
                    $this->set('result', $this->joiningtweetssnodate($text));
                }

                if (empty($tweets)) {
                    $this->Session->setFlash('please check your search criteria it has no results');
                }
            } else {
                $this->Session->setFlash('you are not authorized to filter ');
            }
        }
    }

}

?>